﻿using Studio77.GuessTheWordsWin8.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Windows.Storage;

namespace Studio77.GuessTheWordsWin8.Utils
{
    internal class WordMapLoader
    {
        /// <summary>
        /// 读取应用程序文件
        /// </summary>
        /// <param name="path">文件路径 ，按普通路径来给 /Images/1.jpg</param>
        /// <returns></returns>
        public async static Task<Stream> ReadAppFile(string path)
        {
            Uri baseUri = new Uri("ms-appx://");
            Uri uri = new Uri(baseUri, path);
            try
            {
                StorageFile sf = await StorageFile.GetFileFromApplicationUriAsync(uri);
                if (sf != null)
                {
                    return await sf.OpenStreamForReadAsync();
                }
            }
            catch (Exception ex)
            {

            }
            return null;
        }

        public async static Task<MapInfo> LoadMap(int index)
        {
            MapInfo mapInfo = new MapInfo();
            String fileName = "stage" + index + ".map";
            try
            {

                Stream stream = await ReadAppFile("Stages/" + fileName);
                if (stream != null)
                {
                    //StreamResourceInfo reader = Application.GetResourceStream(new Uri("Stages/" + fileName, UriKind.Relative));
                    using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
                    {

                        // 读取wordCount
                        String c = sr.ReadLine().Trim();
                        String count = GetBase64String(c);
                        int wordCount = int.Parse(count);
                        mapInfo.wordsCount = wordCount;

                        // 读取所有词条
                        List<WordInfo> words = new List<WordInfo>();
                        for (int i = 0; i < wordCount; i++)
                        {
                            String wordComponentTemp = sr.ReadLine();
                            String wordComponent = GetBase64String(wordComponentTemp);
                            String[] compoents = Regex.Split(wordComponent, "--", RegexOptions.IgnoreCase);
                            WordInfo info = new WordInfo();
                            info.pinyin = compoents[0];
                            info.content = compoents[1];
                            info.tip = compoents[2];
                            words.Add(info);
                        }
                        mapInfo.wordList = words;

                        // 读取字符位置
                        List<CharacterLocationInfo> locations = new List<CharacterLocationInfo>();
                        String location64 = sr.ReadLine();
                        int lineIndex = 0;

                        while (location64 != null && location64 != "")
                        {

                            CharacterLocationInfo locationInfo = new CharacterLocationInfo();

                            String location = GetBase64String(location64);

                            String[] locationComponent = Regex.Split(location, ",", RegexOptions.IgnoreCase); ;
                            locationInfo.row = int.Parse(locationComponent[0]);
                            locationInfo.column = int.Parse(locationComponent[1]);

                            if (locationComponent[2] != null
                                    && locationComponent[2] != ("N"))
                            {
                                locationInfo.orientationWordIndex = int.Parse(locationComponent[2]);
                                locationInfo.orientationCharIndex = int.Parse(locationComponent[3]);
                            }
                            if (locationComponent[4] != null
                                    && locationComponent[4] != ("N"))
                            {
                                locationInfo.verticalWordIndex = int.Parse(locationComponent[4]);
                                locationInfo.verticalCharIndex = int.Parse(locationComponent[5]);
                            }
                            locations.Add(locationInfo);

                            location64 = sr.ReadLine();
                            lineIndex++;
                        }

                        mapInfo.charLocationList = locations;

                    }
                }
            }
            catch (Exception ex)
            {

            }

            return mapInfo;
        }

        /// <summary>
        /// 获取base64代码
        /// </summary>
        /// <param name="base64"></param>
        /// <returns></returns>
        static string GetBase64String(string base64)
        {
            byte[] bytes = Convert.FromBase64String(base64);
            return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
        }
    }
}
